package com.example.demo.common.spring;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * spring 工具类
 *
 * @author zhaiding
 */
@Slf4j
public class SpringUtil {

    private SpringUtil() {
    }


    /**
     * 全局的ApplicationContext
     */
    private static final ApplicationContext CONTEXT = ApplicationContextRegister.getContext();

    /**
     * 获取ApplicationContext
     */
    public static ApplicationContext getApplicationContext() {
        return CONTEXT;
    }


    /**
     * 获取 spring bean
     */
    public static Object getBean(String beanName) {
        if (containsBean(beanName)) {
            return getApplicationContext().getBean(beanName);
        }
        return null;
    }

    /**
     * ApplicationContext是否包含该Bean
     */
    public static boolean containsBean(String name) {
        return getApplicationContext().containsBean(name);
    }


    /**
     * 依赖spring框架获取HttpServletRequest
     *
     * @return HttpServletRequest
     */
    public static HttpServletRequest getRequest() {
        HttpServletRequest request = null;
        try {
            ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (Objects.nonNull(requestAttributes)) {
                request = requestAttributes.getRequest();
            }
        } catch (Exception e) {
            log.error("HttpServletRequest error : {}", e.getMessage(), e);
        }
        return request;
    }
}